package com.ghp.web.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 *  替代HttpServlet，让其它的Servlet都继承BaseServlet
 *  目的：重写HttpServlet的service方法，让它能动态调用子类的方法
 */
public class BaseServlet extends HttpServlet {
    /**
     * 使用反射实现动态调用servlet中的方法
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、获取方法名
        //1.1 获取请求路径
        String uri = req.getRequestURI();
        //1.2 获取方法名
        int index = uri.lastIndexOf("/");
        String methodName = uri.substring(index + 1);
        //2、使用反射动态执行方法
        //2.1 获取类对象
        Class<? extends BaseServlet> cls = this.getClass();
        //2.2 获取方法对象
        try {
            Method method = cls.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this, req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
